//
//  PreviewViewController.m
//  Peso Guide
//
//  Created by macbook on 2025/6/13.
//

#import "PreviewViewController.h"
#import <Photos/Photos.h>

@interface PreviewViewController ()

@property (strong, nonatomic) UIImageView *photoView;
@property (strong, nonatomic) UIButton *retakeButton;
@property (strong, nonatomic) UIButton *confirmButton;
@property (strong, nonatomic) UIButton *cancelButton;

@end

@implementation PreviewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    
    [self setupUI];
}

- (void)setupUI {
    
    self.navView.backgroundColor = ColorHex(@"#1A7A35");
    self.titleLabel.text = [Lang set:@"Preview"];
    self.backColor = [UIColor blackColor];
    [self.view addSubview:self.navView];
    [self.backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 照片预览视图
    _photoView = [[UIImageView alloc] initWithFrame:CGRectMake(0, kStarBarHeight, KScreenWidth, KScreenHeight-kStarBarHeight-120-kSafeBottomHeight)];
    _photoView.backgroundColor = [UIColor blackColor];
    _photoView.contentMode = UIViewContentModeScaleAspectFit;
    _photoView.image = self.photo;
    [self.view addSubview:_photoView];
    
    // 底部工具栏
    UIView *toolbar = [[UIView alloc] initWithFrame:CGRectMake(0, KScreenHeight-kSafeBottomHeight-120, KScreenWidth, 120)];
    toolbar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:toolbar];
    
    // 重拍/重选按钮
    NSString *retakeTitle = (self.sourceType == PhotoSourceTypeCamera) ? [Lang set:@"Reshoot"] : [Lang set:@"Reselect"];
    _retakeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _retakeButton.frame = CGRectMake(20, 20, (toolbar.frame.size.width - 60) / 2, 50);
    [_retakeButton setTitle:retakeTitle forState:UIControlStateNormal];
    _retakeButton.backgroundColor = [UIColor clearColor];
    [_retakeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _retakeButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    _retakeButton.layer.cornerRadius = 10;
    [_retakeButton addTarget:self action:@selector(retakeButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [toolbar addSubview:_retakeButton];
    
    // 确认按钮
    _confirmButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _confirmButton.frame = CGRectMake(CGRectGetMaxX(_retakeButton.frame) + 20, 20, (toolbar.frame.size.width - 60) / 2, 50);
    [_confirmButton setTitle:[Lang set:@"Confirm"] forState:UIControlStateNormal];
    _confirmButton.backgroundColor = [UIColor clearColor];
    [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _confirmButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    _confirmButton.layer.cornerRadius = 10;
    [_confirmButton addTarget:self action:@selector(confirmButtonTapped) forControlEvents:UIControlEventTouchUpInside];
    [toolbar addSubview:_confirmButton];
}

- (void)backButtonClick {
    [self dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - 按钮事件处理

- (void)retakeButtonTapped {
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.onRetake) {
            self.onRetake();
        }
    }];
}

- (void)confirmButtonTapped {
    [SVProgressHUD show];
    
    self.retakeButton.enabled = NO;
    self.confirmButton.enabled = NO;
    
    // 异步压缩图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        UIImage *compressedImage = [self compressImage:self.photo toMaxSize:800];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.onConfirm) {
                self.onConfirm(compressedImage);
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        });
    });
}

- (void)cancelButtonTapped {
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 图片压缩

- (UIImage *)compressImage:(UIImage *)image toMaxSize:(NSInteger)maxSizeKB {
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    
    // 质量压缩
    while (imageData.length > maxSizeKB * 1024 && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    
    // 尺寸压缩（如果仍然过大）
    if (imageData.length > maxSizeKB * 1024) {
        UIImage *resultImage = [UIImage imageWithData:imageData];
        CGFloat ratio = sqrt((maxSizeKB * 1024) / (CGFloat)imageData.length);
        CGSize newSize = CGSizeMake(resultImage.size.width * ratio, resultImage.size.height * ratio);
        
        UIGraphicsBeginImageContextWithOptions(newSize, NO, [UIScreen mainScreen].scale);
        [resultImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return newImage;
    }
    
    return [UIImage imageWithData:imageData];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
